package org.shopping.web.commodity;

import org.apache.commons.beanutils.BeanUtils;
import org.shopping.domain.Commodity;
import org.shopping.service.commodity.impl.CommodityServiceImpl;

import javax.servlet.*;
import javax.servlet.http.*;
import javax.servlet.annotation.*;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.util.Map;

@WebServlet(name = "UpdateCommodityController", value = "/UpdateCommodityController")
public class UpdateCommodityController extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doPost(request, response);
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        response.setContentType("text/html;charset=utf-8");
        try {
            // 获取修改后的内容
            Map<String, String[]> parameterMap = request.getParameterMap();
            Commodity commodity = new Commodity();
            // beanutils封装
            BeanUtils.populate(commodity, parameterMap);
            String cid = commodity.getCid();
            // 执行service层方法
            CommodityServiceImpl commodityService = new CommodityServiceImpl();
            boolean flag = commodityService.updateCommodity(commodity, cid);
            if (flag) {
                // 修改成功
                response.sendRedirect(request.getContextPath() + "/index.jsp");
            }
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            e.printStackTrace();
        }

    }
}
